package com.markerhub.controller;

import com.markerhub.common.lang.Result;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/DL")
public class DlController {

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd");

    @PostMapping("/upload")//上传图片
    public Map<String,Object> fileupload(MultipartFile file, HttpServletRequest req) throws FileNotFoundException {
        Map<String ,Object> result = new HashMap<>();
        String originName= file.getOriginalFilename();//前端传过来的文件路径
        System.out.println("判断结果："+originName.endsWith(".png"));
        Boolean filetype=false;
        if(originName.endsWith(".png")){
            filetype=true;
        }
        if(originName.endsWith(".jpg")){
            filetype=true;
        }
        System.out.println("判断结果："+originName.endsWith(".png"));

        if(!filetype){
            System.out.println(originName);
            result.put("status","error");//判断文件格式
            result.put("msg","图片格式不对");
            return result;
        }else if (!filetype){
            System.out.println(originName);
            result.put("status","error");//判断文件格式
            result.put("msg","图片格式不对");
            return result;
        }
        String format = sdf.format(new Date());//根据时间命名文件
        System.out.println(req.getServletContext().getRealPath("/"));
        String realpath=ResourceUtils.getURL("classpath:").getPath()+"/static/img/"+format;
        System.out.println("realpath2:"+realpath);
        //String realpath="E://upfile-spring/"+format;
        //String realpath=ResourceUtils.getURL("classpath:").getPath()+format;
        System.out.println("当前路径："+ ResourceUtils.getURL("classpath:").getPath());
        System.out.println("realpath:"+realpath);
        File folder= new File(realpath);
        if(!folder.exists()){
            folder.mkdirs();
        }
        //新名字拼接
        String newName = UUID.randomUUID().toString()+".png";
        if(originName.endsWith(".png")){
             newName = UUID.randomUUID().toString()+".png";
        }else if (originName.endsWith(".jpg")){
             newName = UUID.randomUUID().toString()+".jpg";
        }else {
             newName = UUID.randomUUID().toString()+".png";
        }
        System.out.println("folder:"+folder.getAbsolutePath());
        try{
            file.transferTo(new File(folder,newName));
            String url = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/img"+format+"/"+newName;
            result.put("status","success");
            result.put("url",url);
        }catch (IOException e){
            result.put("status","error");
            result.put("msg",e.getMessage());
            e.printStackTrace();
        }
        return  result;


    }

    @PostMapping("/delete")
    public Result deletefile(@RequestParam("url") String url) throws FileNotFoundException {
        System.out.println("url:"+url);
        String resultInfo=null;
        String[] fileadd=url.split("img");
        String realpath=ResourceUtils.getURL("classpath:").getPath()+"static/img"+fileadd[1];
        File file = new File(realpath);
        if (file.exists()) {//文件是否存在
            if (file.delete()) {//存在就删了，返回1
                resultInfo =  "1";
            } else {
                resultInfo =  "0";
            }
        } else {
            resultInfo = "文件不存在！";
        }
        System.out.println(resultInfo);

        return Result.succ(resultInfo);
    }


    @PostMapping("/upload2")//原版
    public Map<String,Object> uploadAvatarHandler(@RequestParam("avatar") MultipartFile uploadFile,HttpServletRequest req ) throws IOException {
        //获得项目的类路径
        Map<String ,Object> result = new HashMap<>();
        String path = ResourceUtils.getURL("classpath:").getPath();
        System.out.println("path"+path);
        //空文件夹在编译时不会打包进入target中
        //File uploadDir = new File(path+"/static/avatar/user");
        File uploadDir = new File("E://upfile-spring");
        if (!uploadDir.exists()) {
            System.out.println("上传头像路径不存在，正在创建...");
            uploadDir.mkdir();
        }
        if ( uploadFile != null) {
            //获得上传文件的文件名
            String oldName = uploadFile.getOriginalFilename();
            System.out.println("[上传的文件名]：" + oldName);
            //我的文件保存在static目录下的avatar/user
            File avatar = new File(path + "/static/img/" , oldName);
            try {
                //保存图片
                uploadFile.transferTo(avatar);
                //返回成功结果，附带文件的相对路径
                //result.put("url","/img/"+oldName);
                result.put("url",req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+"/img/"+oldName);
                return result;
            }catch (IOException e) {
                e.printStackTrace();
                result.put("msg",e.getMessage());
                return result;
            }
        }else {
            System.out.println("上传的文件为空");
            result.put("msg","格式错误");
            return result;
        }

    }
}
